package com.wgts.wgts.mvp.view.activity.store;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.common.utils.OSSUtils;
import com.wgts.wgts.R;
import com.wgts.wgts.base.BaseActivity;
import com.wgts.wgts.control.oss.FileUtils;
import com.wgts.wgts.control.oss.OssService;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerEditStoreActivityComponent;
import com.wgts.wgts.dagger.module.EditStoreActivityModule;
import com.wgts.wgts.mvp.presenter.IEditStoreActivityPresenter;
import com.wgts.wgts.mvp.view.IEditStoreActivityView;
import com.wgts.wgts.mvp.view.activity.mycenter.NameLengthFilter;
import com.wgts.wgts.netmodle.req.EditMyCenterMessageRequest;
import com.wgts.wgts.netmodle.resp.EditStoreEntity;
import com.wgts.wgts.netmodle.resp.StoreMsgEntity;
import com.wgts.wgts.tools.AppInfor;
import com.wgts.wgts.tools.MoHuGlide;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/*
 *
 *
 *   data:2018/10/1120:41
 *
 */
@RuntimePermissions
public class EditStoreActivity extends BaseActivity implements IEditStoreActivityView {
    @BindView(R.id.back_btn_image)
    ImageView backBtnImage;
    @BindView(R.id.back_btn_ly)
    LinearLayout backBtnLy;
    @BindView(R.id.include_title)
    TextView includeTitle;
    @BindView(R.id.include_text)
    TextView includeText;
    @BindView(R.id.include_right_image)
    ImageView includeRightImage;
    @BindView(R.id.include_right_ly)
    LinearLayout includeRightLy;
    @BindView(R.id.store_head_image)
    ImageView storeHeadImage;
    @BindView(R.id.store_head_ly)
    RelativeLayout storeHeadLy;
    @BindView(R.id.change_nike_name_et)
    EditText changeNikeNameEt;
    @BindView(R.id.store_nike_name_ly)
    RelativeLayout storeNikeNameLy;
    @BindView(R.id.change_nike_name_ly)
    RelativeLayout changeNikeNameLy;
    @BindView(R.id.store_msg_edit)
    EditText storeMsgEdit;

    public static final int EDIT_STORE_RESULT_OK = 22;
    public static final String STORE_MSG = "store_msg";
    private StoreMsgEntity storeMsgEntity;
    private EditStoreEntity editStoreEntity;
    private int REQUEST_CODE_CHOOSE = 1;
    private static final String FILE_PATH = "com.wgts.wgts.fileprovider";
    private List<Uri> mSelected;
    private String headImage;

    @Inject
    IEditStoreActivityPresenter presenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_store_activity);
        ButterKnife.bind(this);
        includeTitle.setText("店铺介绍");
        Intent intent = getIntent();
        storeMsgEntity = intent.getParcelableExtra(STORE_MSG);
        intView();
    }

    @Override
    public void init() {
        DaggerEditStoreActivityComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .editStoreActivityModule(new EditStoreActivityModule(this))
                .build()
                .inject(this);
    }

    private void intView() {
        editChange();
        MoHuGlide.getInstance().glideImg(this, storeMsgEntity.shopImage, storeHeadImage);
        changeNikeNameEt.setHint(storeMsgEntity.shopName);
        storeMsgEdit.setHint(storeMsgEntity.shopDesc);
    }

    @OnClick({R.id.back_btn_ly, R.id.change_nike_name_ly, R.id.store_head_ly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn_ly:
                finish();
                break;
            case R.id.change_nike_name_ly:
                submitStoreInfo();
                break;
            case R.id.store_head_ly:
                EditStoreActivityPermissionsDispatcher.addIdeaBackImageWithPermissionCheck(this);
                break;
        }
    }

    private void editChange() {
        final InputFilter[] filters = {new NameLengthFilter(24)};
        changeNikeNameEt.setFilters(filters);
        final InputFilter[] filters1 = {new NameLengthFilter(240)};
        storeMsgEdit.setFilters(filters1);

    }

    private void submitStoreInfo(){
        final String name = changeNikeNameEt.getText().toString().trim();
        final String msg = storeMsgEdit.getText().toString().trim();
        if ((name == null || name.equals("")) && (msg == null || msg.equals("")) && (headImage == null || headImage.equals(""))){
            MoHuToast.showToast("未修改信息");
            return;
        }
//        if (name.equals(storeMsgEntity.shopName)){
//            MoHuToast.showToast("名称与之前相同");
//            return;
//        }
        if(mSelected != null && mSelected.size() > 0){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    OssService.getInstance(EditStoreActivity.this).beginupload("head",
                            FileUtils.getRealFilePath(EditStoreActivity.this, mSelected.get(0)),
                            new OssService.ProgressCallback() {
                                @Override
                                public void onProgressCallback(double progress, String url) {
                                    if(progress == 100){
                                        headImage = url;
                                        if (headImage.equals("")){
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    MoHuToast.showToast("图片上传失败");
                                                }
                                            });
                                        }else {
                                            showDialog();
                                            presenter.editStore(name, headImage, msg);
                                        }
                                    }
                                }
                            });
                }
            }).start();
        }else {
            showDialog();
            presenter.editStore(name, headImage, msg);
        }
    }

    @Override
    public void onError(int status, String msg) {
        dialogDismiss();
        MoHuToast.showToast(msg);
    }

    @Override
    public void editStore(EditStoreEntity storeEntity) {
        dialogDismiss();
        editStoreEntity = storeEntity;
        Intent intent = new Intent();
        intent.putExtra(STORE_MSG, editStoreEntity);
        setResult(EDIT_STORE_RESULT_OK, intent);
        finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data ){
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainResult(data);
            MoHuGlide.getInstance().glideImgsFormList(storeHeadImage, mSelected.get(0).toString(), EditStoreActivity.this);
        }
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void addIdeaBackImage(){
        Matisse.from(EditStoreActivity.this)
                .choose(MimeType.ofAll(), false)
                .countable(true)
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, FILE_PATH))
                .maxSelectable(1)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new com.wgts.wgts.control.matisse.GlideEngine()) // 使用的图片加载引擎
                .forResult(REQUEST_CODE_CHOOSE); // 设置作为标记的请求码
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void addIdeaBackImageWrong(){
        Toast.makeText(EditStoreActivity.this,
                "获取权限失败，可能无法上传照片", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EditStoreActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
